package com.thiswhyme.openfeign.gson.adapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 用于Calendar的格式化
 * @author thiswhyme
 * @date: 2020/8/20
 */
public class CalendarAdapter implements GsonBizAdapter<Calendar> {

    @Override
    public Type getType() {
        return null;
    }

    @Override
    public Class getClazz() {
        return Calendar.class;
    }

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 日期格式转化的样式字符串
     */
    private String dateFormat;

    /**
     * 默认构造器
     */
    public CalendarAdapter() {
        this(DEFAULT_PATTERN);
    }

    /**
     * 指定格式的构造函数
     * 
     * @param dateFormat
     */
    public CalendarAdapter(String dateFormat) {
        super();
        this.dateFormat = dateFormat;
    }

    public String getDateFormat() {
        return this.dateFormat;
    }
    
    private SimpleDateFormat fetchDateFormat() {
        return new SimpleDateFormat(this.dateFormat);
    }

    @Override
    public JsonElement serialize(Calendar calendar, Type type, JsonSerializationContext context) {
        String value = null;
        if (calendar == null) {
            value = "";
        } else {
            value = this.fetchDateFormat().format(calendar.getTime());
        }

        return new JsonPrimitive(value);
    }

    @Override
    public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        Calendar calendar = Calendar.getInstance();
        if (null != json) {
            try {
                Date date = this.fetchDateFormat().parse(json.getAsString());
                calendar.setTime(date);
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
        return calendar;
    }
}